#include "http_post.h"

#include <QFile>
#include <QNetworkCookie>

Http_Post::Http_Post(QObject *parent) : QObject(parent)
{

}

Http_Post::~Http_Post()
{

}

void Http_Post::post(QString url, QString str, bool needCookie)
{
    QNetworkRequest request(url);

    // webwx use json content type as HTTP POST header
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    if (needCookie) {
        QFile file(QWXDIR + "/" + COOKIE_FILENAME);
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream out(&file);
            QList<QNetworkCookie> cookies = QNetworkCookie::parseCookies(out.readAll().toUtf8());

            QVariant var;
            var.setValue(cookies);
            request.setHeader(QNetworkRequest::CookieHeader, var);
        }
    }

    m_sslErrorConnection = connect(&m_nam, &QNetworkAccessManager::sslErrors,
                                [this](QNetworkReply* reply, const QList<QSslError> & errors) {
                                    reply->ignoreSslErrors(errors);
                                });

    m_finishConnection = connect(&m_nam, &QNetworkAccessManager::finished,
                                [this](QNetworkReply* reply) {
                                    this->finished(reply);

                                    disconnect(m_sslErrorConnection);
                                    disconnect(m_finishConnection);
                                });

    m_nam.post(request, str.toUtf8());
}
